package com.lujieni.springbootsecurity.utils;

import com.lujieni.springbootsecurity.po.UserDO;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * @Author：Jie Ni
 * @Date: 2025/10/17 10:28
 * @Description:
 */
public class SecurityFrameworkUtils {

    public static String obtainAuthorization(HttpServletRequest request, String header) {
        return request.getHeader(header);
    }

    public static void setLoginUser(UserDO loginUser) {
        // 创建认证对象 不在认证对象中保存密码!!!
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, Collections.emptyList());
        // 将认证信息存入Security上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }

    public static Long getLoginUserId() {
        UserDO loginUser = getLoginUser();
        return loginUser != null ? loginUser.getId() : null;
    }

    public static UserDO getLoginUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        } else {
            return authentication.getPrincipal() instanceof UserDO ? (UserDO)authentication.getPrincipal() : null;
        }
    }

    public static Authentication getAuthentication() {
        SecurityContext context = SecurityContextHolder.getContext();
        return context == null ? null : context.getAuthentication();
    }

}
